# -*- coding:utf8 -*-
'''
Created on 2016年8月10日
@author: zhaoxiang
'''
from __future__ import print_function
import os,sys
reload(sys)
sys.setdefaultencoding("utf8")
import HiveClient
import format_time
from DB import DB
import gua
import ConfigParser

reload(sys)
conf = ConfigParser.ConfigParser() 
conf.read("config_sql.cfg")

#获取指定时间戳区间内发送的job
def getJobs(starttime, endtime):
    qyer_db = DB(gua.conn_ra["host"], gua.conn_ra["username"], gua.conn_ra["password"], gua.conn_ra["db"], gua.conn_ra["port"])
    sql=conf.get("main", "jobs") % (starttime, endtime)
    print(sql)
    qyer_db.execute(sql)
    result_set = qyer_db.fetchall()
    qyer_db.close()
    return result_set

################################################
#根据job_id查指定时间戳区间内打开推送的人数
#根据app_name查指定时间戳区间内打开APP的人数
################################################
def getOpen_users(job_id, app_name,beginTimestamp,endTimestamp,interval):
    #起始日期，截止日期，可能跨天，判断一下
    logdate1=format_time.timeStamp2DateStr(beginTimestamp)
    logdate2=format_time.timeStamp2DateStr(endTimestamp)
    if logdate1==logdate2:
        date_condition= '"%s"' % (logdate1,)
    else:
        date_condition= '"%s","%s"' % (logdate1,logdate2)
    #打开推送    
    open_push_sql=conf.get("main", "open_push") % (date_condition,beginTimestamp,endTimestamp,job_id)
    #打开APP
    open_app_sql=conf.get("main", "open_app") % (date_condition,beginTimestamp,endTimestamp,app_name)
    #推送的人中打开APP的
    open_app_by_push_sql=conf.get("main", "open_app_push") % (date_condition,date_condition,beginTimestamp,endTimestamp,job_id,app_name)
    
    sql=open_push_sql+";"+open_app_by_push_sql +";"
    if interval==3:
        sql=sql +  open_app_sql +";"
    print(sql)
    result_set=HiveClient.execute(sql)
    
    print("\nhivesql:\n"+sql+"\n")
    print("******************************result_set***********************: " + str(result_set))
    
    if len(result_set) == 2:
        open_push_users=result_set[0][0]
        open_app_by_push_users=result_set[1][0]
        return (open_push_users,open_app_by_push_users,0)
    elif len(result_set) == 3:
        open_push_users=result_set[0][0]
        open_app_users=result_set[2][0]
        open_app_by_push_users=result_set[1][0]
        return (open_push_users,open_app_by_push_users,open_app_users)
    return (0,0,0)

#ios推送人数
def get_ios_push_info(job_id):
    qyer_db = DB(gua.conn_engine["host"], gua.conn_engine["username"], gua.conn_engine["password"], gua.conn_engine["db"], gua.conn_engine["port"])
    sql=conf.get("main", "ios_push_info") % job_id
    print(sql)
    qyer_db.execute(sql)
    result_set = qyer_db.fetchall()
    qyer_db.close()
    if result_set:
        return (result_set[0][0],result_set[0][1])
    return (0,0)

#android推送人数
def get_android_push_info(job_id):
    qyer_db = DB(gua.conn_ra["host"], gua.conn_ra["username"], gua.conn_ra["password"], gua.conn_ra["db"], gua.conn_ra["port"])
    sql=conf.get("main", "android_push_info") % job_id
    print(sql)
    qyer_db.execute(sql)
    result_set = qyer_db.fetchall()
    qyer_db.close()
    if result_set:
        return result_set[0][0]
    return 0

#3小时统计
def update_stat_3_hours(rawdata):
    qyer_db = DB(gua.conn_ra["host"], gua.conn_ra["username"], gua.conn_ra["password"], gua.conn_ra["db"], gua.conn_ra["port"])
    sql=conf.get("main", "update_stat_3_hours") % rawdata
    print(sql)
    qyer_db.execute(sql)
    qyer_db.close()

#12小时统计
def update_stat_12_hours(rawdata):
    qyer_db = DB(gua.conn_ra["host"], gua.conn_ra["username"], gua.conn_ra["password"], gua.conn_ra["db"], gua.conn_ra["port"])
    sql=conf.get("main", "update_stat_12_hours") % rawdata
    print(sql)
    qyer_db.execute(sql)    
    qyer_db.close()
    
if __name__ == '__main__':
    if len(sys.argv) == 1:
        print("usage: %s 3|12 [Y-m-d HH:MM:SS]" % sys.argv[0], sep=' ', end='\n', file=sys.stderr)
        sys.exit(1)
    if len(sys.argv) == 2:
        curTime=format_time.get_now()
    elif len(sys.argv) == 3:
        curTime=sys.argv[2]
    interval=int(sys.argv[1])
    
    #统计截止时间
    curTimestamp=format_time.dateStr2Timestamp(curTime)
    #发送时间
    sendTime_begin=format_time.dateStr2Timestamp(curTime,hours=(-interval-1))
    sendTime_end=format_time.dateStr2Timestamp(curTime,hours=(-interval))
    
    #指定时间段内发送的jobs
    job_set=getJobs(sendTime_begin,sendTime_end)
    if job_set:
        for row in job_set:
            job_id=row[0]
            app_name=row[1]
            #统计人数
            (open_push_users,open_app_by_push_users,open_app_users)=getOpen_users(job_id,app_name,sendTime_begin,curTimestamp,interval)
            if interval==3:
                if "ios" in app_name:
                    (push_nums,success_nums)=get_ios_push_info(job_id)
                elif "androi" in app_name:
                    push_nums=get_android_push_info(job_id)
                    push_nums=push_nums if push_nums else 0
                    success_nums=push_nums;
                rowdata=(job_id, job_id, push_nums,success_nums,open_push_users,open_push_users,open_app_by_push_users,open_app_users)
                update_stat_3_hours(rowdata)
            elif interval==12:
                rowdata=(open_push_users, job_id)
                update_stat_12_hours(rowdata)
            else:
                print("in %s hours, open_push_users:%s, open_app_by_push_users:%s" % (interval,open_push_users,open_app_by_push_users))
    sys.exit(0)            